package com.example.okhttp;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/12/5.
 */

public class OkhttpUtil {

    public static OkHttpClient okHttpClient = new OkHttpClient();

    public static void getContent(String url, Callback callback){
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }

    public static String getContent(String url){
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            return response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String post(String url, Map<String, String> map){

        FormBody.Builder build = new FormBody.Builder();
        Set<String> keys = map.keySet();
        for(String key:keys){
            build.add(key,map.get(key));
        }
        RequestBody requestBody = build.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response responce =okHttpClient.newCall(request).execute();
            return responce.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
